/*
 ============================================================================
 Name        : Bowling.c
 Author      : gangz
 ============================================================================
 */

#include <stdio.h>
#include <stdlib.h>
#include "Bowling.h"

void Bowling_init(struct BOWLING* game)
{
	game->score = 0;
	game->currentRoll = 0;
	for (int i=0;i<sizeof(game->roll)/sizeof(game->roll[0]);i++)
		game->roll[i]=0;
	for (int i=0;i<FRAMES_NUM;i++){
		game->bounsCount[i] = 0;
	}
	game->isInBonusRoll = FALSE;
	game->isGameOver = FALSE;
}

int RollToFrameIndex(int rollIndex){
	return rollIndex/2;
}

int RollToIndexInFrame(int rollIndex){
	return rollIndex%2;
}

void Bowling_checkSpare(struct BOWLING* game){
	if (RollToIndexInFrame(game->currentRoll)==1) //last roll in a frame
	{
		if (game->roll[game->currentRoll] + game->roll[game->currentRoll-1]==10)
		{
			game->bounsCount[game->currentRoll/2]  = 1;
		}
	}
}

void Bowling_checkStrike(struct BOWLING* game){
	if (game->roll[game->currentRoll]==10 && game->currentRoll<20){
		game->bounsCount[RollToFrameIndex(game->currentRoll)] = 2;
	}
}

void Bowling_moveToNextRoll(struct BOWLING* game){
	if ((game->currentRoll%2)==0 && game->roll[game->currentRoll]==10) //first roll in a frame and is a strike
	{
		game->currentRoll++; //skip to next frame
	}
	game->currentRoll++;
	if (game->currentRoll>=20)
	{

		if (game->bounsCount[FRAMES_NUM-1]>0 ||game->bounsCount[FRAMES_NUM-2]>0)
		{
			game->isInBonusRoll=TRUE;
			game->isGameOver = FALSE;
		}
		else
		{
			game->isGameOver = TRUE;
			game->isInBonusRoll=FALSE;
		}
	}
}

void Bowling_addBonus(struct BOWLING* game){
	for (int i=0;i<10;i++){
		if (game->bounsCount[i] >0)
		{
			game->score +=game->roll[game->currentRoll];
			game->bounsCount[i]--;
		}
	}
}

void Bowling_addScore(struct BOWLING* game){
	game->score+=game->roll[game->currentRoll];
}

void Bowling_roll(struct BOWLING* game, int pins){
	game->roll[game->currentRoll]=pins;
	if (game->currentRoll<20)
		Bowling_addScore(game);
	Bowling_addBonus(game);
	Bowling_checkSpare(game);
	Bowling_checkStrike(game);
	Bowling_moveToNextRoll(game);
}
